package com.ruoyi.data.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;

import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.excel.ExcelResult;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.data.domain.bo.DataListBatchBo;
import com.ruoyi.data.domain.listener.DataListImportListener;
import com.ruoyi.data.domain.vo.DataListImportVo;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.data.domain.vo.DataListVo;
import com.ruoyi.data.domain.bo.DataListBo;
import com.ruoyi.data.service.IDataListService;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 数据列表
 *
 * @author ruoyi
 * @date 2023-10-26
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/dataList/dataList")
public class DataListController extends BaseController {

    private final IDataListService iDataListService;

    /**
     * 查询数据列表列表
     */
    @SaCheckPermission("dataList:dataList:list")
    @GetMapping("/list")
    public TableDataInfo<DataListVo> list(@Validated(QueryGroup.class)DataListBo bo, PageQuery pageQuery) {
        return iDataListService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出数据列表列表
     */
    @SaCheckPermission("dataList:dataList:export")
    @Log(title = "数据列表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(DataListBo bo, HttpServletResponse response) {
        List<DataListVo> list = iDataListService.queryList(bo);
        ExcelUtil.exportExcel(list, "数据列表", DataListVo.class, response);
    }

    /**
     * 获取数据列表详细信息
     *
     * @param dataId 主键
     */
    @SaCheckPermission("dataList:dataList:query")
    @GetMapping("/{dataId}")
    public R<DataListVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable String dataId) {
        return R.ok(iDataListService.queryById(dataId));
    }

    /**
     * 新增数据列表
     */
    @SaCheckPermission("dataList:dataList:add")
    @Log(title = "数据列表", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody DataListBo bo) {

//        if (!LoginHelper.isAdmin() && bo.getUserId()!= null){
//            throw new ServiceException("非管理员无法使用userId插入！");
//        }

        return toAjax(iDataListService.insertByBo(bo));
    }

    /**
     * 修改数据列表
     */
    @SaCheckPermission("dataList:dataList:edit")
    @Log(title = "数据列表", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody DataListBo bo) {
        return toAjax(iDataListService.updateByBo(bo));
    }

    /**
     * 删除数据列表
     *
     * @param dataIds 主键串
     */
    @SaCheckPermission("dataList:dataList:remove")
    @Log(title = "数据列表", businessType = BusinessType.DELETE)
    @DeleteMapping("/{dataIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable String[] dataIds) {
        return toAjax(iDataListService.deleteWithValidByIds(Arrays.asList(dataIds), true));
    }

    /**
     * 获取导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil.exportExcel(new ArrayList<>(), "数据列表", DataListImportVo.class, response);
    }

    /**
     * 导入数据
     *
     * @param file          导入文件
     * @param updateSupport 是否更新已存在数据
     */
    @Log(title = "导入数据", businessType = BusinessType.IMPORT)
    @SaCheckPermission("dataList:dataList:import")
    @PostMapping(value = "/importData", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Void> importData(@RequestPart("file") MultipartFile file, boolean updateSupport) throws Exception {
        ExcelResult<DataListImportVo> result = ExcelUtil.importExcel(file.getInputStream(), DataListImportVo.class, new DataListImportListener(updateSupport));
        return R.ok(result.getAnalysis());
    }



    /**
     * 批量转移
     *
     * @param bo
     */
    @Log(title = "批量转移", businessType = BusinessType.UPDATE)
    @PostMapping("/batchPaste")
    public R<Void> batchPaste(@Validated(EditGroup.class) @RequestBody DataListBatchBo bo
    ) {
        return toAjax(iDataListService.batchPaste(LoginHelper.getUserId(), Arrays.asList(bo.getDataIds()),
            bo.getBeforeClassificationId(),
            bo.getClassificationId(),
            bo.getStatus(),
            bo.getSourceStatus()
        ));
    }

    /**
     * 清空该分类下数据
     * type 0 未读 1已读 2全部
     *
     * @param dataIds 主键串
     */
    @SaCheckPermission("dataList:dataList:remove")
    @Log(title = "数据列表清空", businessType = BusinessType.DELETE)
    @DeleteMapping("/removeDataListByDataClassificationId/{dataIds}/{type}")
    public R<Void> removeDataListByDataClassificationId(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] dataIds,
                                                        @PathVariable int type
    ) {
        return toAjax(iDataListService.removeDataListByDataClassificationId(Arrays.asList(dataIds), true, type));
    }

    /**
     * 按搜索配置清空该分类下数据
     *
     * @param classificationId 主键串
     */
    @Log(title = "按搜索配置清空该分类下数据", businessType = BusinessType.DELETE)
    @DeleteMapping("/removeDataListByDataClassificationIdByConfigJson/{classificationId}")
    public R<Void> removeDataListByDataClassificationIdByConfigJson(
                                                        @PathVariable Long classificationId
    ) {
        return toAjax(iDataListService.removeDataListByDataClassificationIdByConfigJson(classificationId));
    }
}
